<template>
    <div class="">
      <el-upload
        class="avatar-uploader"
        :action="uploadAction"
        :show-file-list="false"
        :on-success="uploadSuccess"
        :before-upload="uploadBefore">
        <img v-if="single_file_url" :src="single_file_url" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </div>
  </template>
  
  <script>
  import { getAdminToken } from "@/utils/auth";
  import { uploadURL } from "@/api/admin/common";
  
  export default {
    name: "FileUpload",
    props: {
      tipText: {
        type: String,
        default() {
          return "";
        },
      },
      // 多文件
      fileList: {
        type: Array,
        default() {
          return [];
        },
      },
      // 单文件
      singleFile: {
        type: String,
        default() {
          return ""
        },
      },
      // 是否显示已上传文件列表
      showFileList: {
        type: Boolean,
        default: false,
      },
      // 多文件上传数量
      limit: {
        type: Number,
        default: 9,
      },
      // 上传图片大小最大限制(单位：KB)
      imageMaxSize: {
        type: Number,
        default: 5120,
      },
      // 上传文件大小最大限制(单位：M)
      maxSize: {
        type: Number,
        default: 100,
      },
      // 上传文件类型
      accept: {
        type: String,
        default: "image/jpeg, image/png, image/gif",
      },
      uploadData: {
        type: Object,
        default() {
          return {
            folder: "local",
            place: "",
            multi: this.showFileList,
            total_count: this.limit,
            count: 0,
          };
        },
      },
      uploadIcon: {
        type: String,
        default: "el-icon-plus",
      },
      // 是否要显示文件
      isShowFile: {
        type: Boolean,
        default: true,
      },
      // 是否按钮上传
      isButton: {
        type: Boolean,
        default: false,
      },
      // 按钮上传对应按钮名称
      buttonText: {
        type: String,
        default: "选择文件",
      },
    },
    data() {
      return {
        imageUrl:'',
        loading: "",
        /*fileList: [
          //{name:'', url: ''}
        ],*/
        single_file_url: "",
  
        uploadHeaders: { token: getAdminToken() },
        uploadAction: uploadURL(), // 文件上传地址
        /*uploadData: {
          type: 'image'
        },*/
        dialogImageVisible: false,
        dialogImageUrl: "",
      };
    },
    watch: {
      singleFile: function (val, oldval) {
        if (val) {
          this.single_file_url = val;
        }
      },
    },
    created() {
      if (this.singleFile) {
        this.single_file_url = this.singleFile;
      }
    },
    methods: {
      uploadBefore(file) {
        this.loading = this.$loading({
          lock: true,
          text: "文件上传中...",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });
        // let extArr = this.accept.split(",");
        const imageAccept = "image/jpeg, image/png, image/gif";
        // const imageAccept = this.accept;
        const isFileExt = this.accept.includes(file.type);
        let isFileSize = true;
        if (!isFileExt) {
          this.loading.close();
          this.$messages.warning("请上传" + this.accept + "文件");
        } else {
          if (file.type && imageAccept.includes(file.type)) {
            isFileSize = file.size / 1024 < this.imageMaxSize;
            if (!isFileSize) {
              this.loading.close();
              this.$messages.warning(
                "文件大小不能超过 " + 5 + "MB!"
                // "图片大小不能超过 " + this.imageMaxSize + "KB!"
              );
            }
          } else {
            isFileSize = file.size / 1024 / 1024 < this.maxSize;
            if (!isFileSize) {
              this.loading.close();
              this.$messages.warning("文件大小不能超过 " + this.maxSize + "M!");
            }
          }
        }
  
        return isFileExt && isFileSize;
      },
      uploadSuccess(res, file) {
        if (res.status === 1) {
          this.single_file_url = URL.createObjectURL(file.raw);
          if (this.showFileList) {
            this.fileList.push({
              id: new Date().getTime(),
              name: "",
              url: res.data.full_filepath,
              path: res.data.filepath,
            });
          } else {
            if (this.isShowFile) {
                this.single_file_url = res.data.full_filepath;
            }

          }
  
          this.uploadCBK();
          this.loading.close();
          this.$messages.success(res.msg);
        } else {
          this.loading.close();
          this.$messages.error(res.msg);
        }
      },
      uploadError(res) {
        this.loading.close();
        this.$messages.error(res.msg || "上传出错");
      },
      uploadRemove(file, fileList) {
        //this.fileList.splice(this.fileList.findIndex(item => item.url === file.url), 1)
        var index = this.fileList.indexOf(file);
        if (index !== -1) {
          this.fileList.splice(index, 1);
        }
        this.uploadCBK();
      },
      uploadPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogImageVisible = true;
      },
  
      // 上传回调
      uploadCBK() {
        //console.log(this.fileList)
        if (this.showFileList) {
          this.$emit("uploadCallback", this.fileList);
        } else {
          this.$emit("uploadCallback", this.singleFile);
        }
      },
     
    },
  };
  </script>
  <style lang="scss" scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 60px;
    height: 60px;
    line-height: 60px;
    text-align: center;
  }
  .avatar {
    width: 60px;
    height: 60px;
    display: block;
  }
  .Img:hover {
    .closeImg {
      z-index: 2;
    }
  }
  .closeImg {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: -1;
    background-color: #00000050;
    border-radius: 5px;
    text-align: center;
    line-height: 90px;
    color: #ffff;
    i {
      cursor: pointer;
    }
  }
  </style>
  